package io.renren.ssh;

import java.io.Closeable;
import java.io.IOException;

import io.renren.common.exception.RRException;
import io.renren.modules.systemconfig.entity.SystemConfigServersEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public abstract class BaseJchClient implements Closeable {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
    protected final static int DEFAULT_CONN_TIMEOUT = 60000;
    protected Session session = null;
    protected SystemConfigServersEntity serverInfo;

    public BaseJchClient(SystemConfigServersEntity serverInfo) throws Exception {
        this.serverInfo = serverInfo;
    }

    public Session newSession(SystemConfigServersEntity serverInfo) throws Exception {
        try {
            JSch jsch = new JSch();
            Session newSession = jsch.getSession(serverInfo.getLoginName(), serverInfo.getIpAddr(), 22);
            newSession.setPassword(serverInfo.getSshPwd());
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            newSession.setConfig(config);
            newSession.setServerAliveInterval(10000);
            return newSession;
        } catch (JSchException e) {
            if ("Auth fail".equals(e.getMessage()) || "Auth cancel".equals(e.getMessage())) {
                throw new RRException("远程连接用户验证失败", 4001);
            }
            throw new Exception(e);
        }
    }

    public void conn() throws Exception {
        try {
            if (session == null) {
                session = newSession(serverInfo);
            }
            if (!session.isConnected()) {
                session.connect(DEFAULT_CONN_TIMEOUT);
            }
        } catch (JSchException e) {
            logger.error("ftp连接异常,ip:{},ex:{}", serverInfo.getIpAddr(), e);
            if ("Auth fail".equals(e.getMessage()) || "Auth cancel".equals(e.getMessage())) {
                session = null;
                throw new RRException("远程连接用户验证失败", 4001);
            }
            throw new Exception(e);
        }
    }

    @Override
    public void close() throws IOException {
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
        session = null;
        logger.debug("远程连接关闭,ip={}", serverInfo.getIpAddr());
    }


}